package com.crm.system.controller.cluePoolManager;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.PathUtil;
import com.crm.model.dto.CustomerDTO;
import com.crm.model.dto.InsertClueCallable;
import com.crm.model.entity.cluePoolManager.Clue;
import com.crm.model.vo.cluePoolManager.ClueImportVO;
import com.crm.system.service.cluePoolManager.ClueImportService;
import com.crm.system.service.cluePoolManager.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author luojie
 * @date 2021/1/26 14:45
 */
@RestController
@RequestMapping("/clueImport")
@Slf4j
public class ClueImportController {

    @Autowired
    private ClueImportService clueImportService;

    /**
     * 线索导入功能
     * @param request
     * @param file
     * @return
     */
    @PostMapping("/clueImport")
    public DataResponse clueImport(HttpServletRequest request,
                                   @RequestParam MultipartFile file,
                                   @RequestParam Integer clueType,
                                   @RequestParam Integer clueStatus,
                                   @RequestParam String poolId) throws IOException {
        JSONObject jsonObject = new JSONObject();
        try {
            ExcelUtil excelUtil = new ExcelUtil();
            List<ClueImportVO> list = excelUtil.excelImport(file.getInputStream(), ClueImportVO.class);//1.读取前端的excel文件并转换成list集合
            if (list == null || list.size() == 0) {
                return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
            }

            //导入线程
            jsonObject = clueImportService.importClueSingle(list,clueType,clueStatus,poolId);

            //线索池容量是否已超
            Boolean ifMoreClueCapacity = jsonObject.getBoolean("moreClueCapacity");
            if(ifMoreClueCapacity){
                return new DhResponse(ResponseCodeEnum.IMPORT_COUNT_EXCEEDS_CAPACITY.getResponseCode());
            }


        } catch (Exception e) {
            log.error("clueImport error:", e);
        }
        //返回导入数量、重复数量
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),jsonObject);
    }

    /**
     * 线索
     * @param response
     */
    @GetMapping("/downloadClueTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        InputStream fis = null;
        OutputStream os = null;
        String path = "";
        try {
            String fileName="线索导入模板.xls";
            //根据系统来判断取相对路径还是绝对路径
            String osName = System.getProperty("os.name");
            if (osName.toLowerCase().startsWith("win")) {
                path = Thread.currentThread().getContextClassLoader().getResource("").getPath()+ PathUtil.getDownPath()+"clue.xls";
            } else {
                path = PathUtil.getDownPath()+"clue.xls";
            }

            fileName = new java.net.URLDecoder().decode(fileName, "utf-8");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));
            //以流的形式下载文件
            fis = new BufferedInputStream(new FileInputStream(path));
            //excel类型为xlsx下面对象用XSSFWorkbook，xls类型对象用HSSFWorkbook
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fis);
            os = new BufferedOutputStream(response.getOutputStream());
            hssfWorkbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("downloadClueTemplate error:", e);
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e1) {
                    log.error("downloadClueTemplate error:", e1);
                }
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e2) {
                    log.error("downloadClueTemplate error:", e2);
                }
            }
        }
    }
}
